package cate.game.rank.history;

import cate.common.table.rank.row.IRewardRankRow;
import cate.game.GameBody;
import cate.game.db.mongo.kv.KvMongo;
import cate.game.rank.po.Rank;
import easy.java.dev.note.NoteField;
import lombok.ToString;
import org.springframework.data.annotation.Transient;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@ToString
public class RankHistorySPO extends KvMongo {
    @Transient
    public transient GameBody gameBody;

    @NoteField(value = "排名奖励达成历史")
    public Map<Integer, Map<Integer,RankReachHistory>> history;

    @Override
    public String getKeyPrefix() {
        return KvMongo.KEY_RANK;
    }

    @Override
    public void initialize() {
        if(history == null){
            history = new HashMap<>();
        }
    }

    public void initialize(GameBody gameBody) {
        this.gameBody = gameBody;
        this.initialize();
    }

    public synchronized void record(int rankId, Rank rank){
        List<IRewardRankRow> reachRows = gameBody.table.rank.getReachRows(rankId, rank.value);
        history.putIfAbsent(rankId, new HashMap<>());
        Map<Integer,RankReachHistory> hisMap;
        for(IRewardRankRow reachRow : reachRows){
            hisMap = history.get(rankId);
            if(!hisMap.containsKey(reachRow.getRewardId())){
                hisMap.put(reachRow.getRewardId(), createHistory(rankId, reachRow.getRewardId(), rank));
            } else {
                RankReachHistory history = hisMap.get(reachRow.getRewardId());
                if (!history.existRecord(rank.owner.uid)) {
                    if (!history.isFull()) {
                        history.addRecord(createRecord(rank));
                    }
                }
            }
        }
    }

    private RankReachHistory createHistory(int rankId, int rewardId, Rank rank){
        RankReachHistory his = new RankReachHistory();
        his.rankId = rankId;
        his.rewardId = rewardId;
        his.addRecord(createRecord(rank));
        return his;
    }

    private RankReachRecord createRecord(Rank rank){
        RankReachRecord record = new RankReachRecord();
        record.srvId = rank.owner.base.srvId;
        record.uid = rank.owner.base.uid;
        record.level = rank.owner.base.level;
        record.name = rank.owner.base.name;
        record.time = System.currentTimeMillis();
        record.headFrame = rank.owner.base.headFrame.copy();
        record.headIcon = rank.owner.base.headIcon.copy();
        return record;
    }

    public Map<Integer, RankReachHistory> getRankHistory(int rankId){
        return history.getOrDefault(rankId, new HashMap<>());
    }
}
